
const { app,ipcMain,BrowserWindow } = require('electron')

var stockCfg = require('../../config/stock.json');

let { init, exec, sql, transaction } = require('mysqls')

var sqlMgr={
  isCon : false,
  getCon(cb){
    if(this.isCon) return;
    var dbInfo = {
      host     : stockCfg.db.host,
      port     : stockCfg.db.port || 3306,
      user     : stockCfg.db.user,
      password : stockCfg.db.password,
      database : stockCfg.db.database,
    }
    console.log('connect db by:',dbInfo);       
    init(dbInfo);
    exec("select version();").then(res=>{
      this.isCon = true;
      cb();
    }).catch(err=>{
      cb(err)
    });

  },
  reCon(cb){
    this.isCon = false;
    this.getCon(cb);
  },
  getSucc(data,param){
    var res = { succ: true, err:"", data:data }
    if(param && param.cb){
      param.cb(res);
    }
    return res;
  },
  getFail(err,param){
    console.error("db exec error",err)
    var res = { succ: false, err:err.message, data:null }
    if(param && param.cb){
      param.cb(res);
    }
    return res;
  },
  insertHis(param){
    sql.table('tradehis').data(param.objInfo).insert(true).exec().then(res=>{
      this.getSucc(res,param)
    }).catch(err=>{
      this.getFail(err,param)
    });
  },
  queryHis(param){
    sql.table('tradehis').where(param.objInfo).select(true).exec().then(res=>{
      this.getSucc(res,param)
    }).catch(err=>{
      this.getFail(err,param)
    });
  },
  getCodeList(param){
    exec("select distinct code,name FROM tradehis  order by day desc,time desc").then(res=>{
      this.getSucc(res,param)
    }).catch(err=>{
      this.getFail(err,param)
    });
  },
  insertMoneyInfo(param){
    sql.table('moneyinfo').data(param.objInfo).insert(true).exec().then(res=>{
      this.getSucc(res,param)
    }).catch(err=>{
      this.getFail(err,param)
    });
  },
  async insertStore(param){
    var list = param.objInfo;
    if(list.length<0) return;
    const curList = await sql.table('store').where({day:list[0].day}).select(true).exec();
    if(curList.length>0){
      this.getFail({message:"已存在"},param)
      return;
    }
    list.map((row)=>{
      sql.table('store').data(row).insert(true).exec()
    });

    this.getSucc("",param)
  },
  async insertToday(param){
    var list = param.objInfo;
    if(list.length<0) return;
    await exec("delete from todayinfo");
    list.map((row)=>{
      sql.table('todayinfo').data(row).insert(true).exec()
    });

    this.getSucc("",param)
  },
  async commonQry(param){
    var respInfo = {
      total:0,
      records: []
    };
    if(param.count){
      var tmpsql = this.commonGetTotal(param);
      console.info("commonQry-sql-count:" , tmpsql)
      respInfo.total = await tmpsql.exec();
      respInfo.total = respInfo.total[0]["COUNT(1)"]
    }
    var qrysql = this.commonGetQuery(param);
    console.info("commonQry-sql:" , qrysql)
    try{
      respInfo.records = await qrysql.exec();
      this.getSucc(respInfo,param)
    }catch(ex){
      console.info("commonQry-error-sql:" , ex)
      this.getFail(ex,param)
    }

    // console.info("commonQry-sql:" , tmpsql)
    // tmpsql.exec().then(res=>{
    //   this.getSucc(res,param)
    // }).catch(err=>{
    //   this.getFail(err,param)
    // });
  },
  async execSql(param){
    console.info("execSql-sql:" , param.sql)
    var res = await exec(param.sql);
    this.getSucc(res,param)
  },
  commonGetTotal(param){
    var tmpsql = sql.count("1").table(param.table).where(param.objInfo);
    if(param.group){
      tmpsql.group(param.group)
    }
    tmpsql.select(true);
    return tmpsql
  },
  commonGetQuery(param){
    var tmpsql = sql.table(param.table).where(param.objInfo);
    if(param.group){
      tmpsql.group(param.group)
    }
    if(param.order){
      tmpsql.order(param.order)
    }
    if(param.pInfo){
      tmpsql.page(param.pInfo)
    }
    tmpsql.select(true);
    return tmpsql
  }
}

sqlMgr.getCon((err)=>{
  if(err){
    console.error("db connect error:",err);
  }else{
    console.error("db connect success");
  }
});

ipcMain.on("reCon",(event)=>{
  try{
    sqlMgr.reCon((err)=>{
      event.sender.send('reConRes', err);
    });
  }catch(ex){
    event.sender.send('reConRes', "数据连接失败:"+ex.message);
  }
});
 
/**
 * param{
 *  type:  "insertHis",
 *  name: "insertHis",
 *  objInfo: {
 *    sqlInfo
 *  }
 * }
 */
ipcMain.on("doSql",(event,param)=>{
  param.name = param.name || param.type;
  try{
    if(sqlMgr.isCon){
      param.cb=(res)=>{
        event.sender.send(param.name+'Res', res);
      }
      if(param.execSql){
        sqlMgr.execSql(param);
      }else if(sqlMgr[param.type]){
        sqlMgr[param.type](param);
      }else{
        event.sender.send(param.name+'Res', sqlMgr.getFail("操作方法不存在:"+param.type));
      }
    }else{
      event.sender.send(param.name+'Res', sqlMgr.getFail("数据库未连接"));
    }
  }catch(ex){
    console.error("db error",ex);
    event.sender.send(param.name+'Res', sqlMgr.getFail("数据库操作失败:"+ex.message));
  }
});
 
// connection.connect();
 
// connection.query('select * from stock_event limit 10', function (error, results, fields) {
//   debugger;
//   if (error) throw error;
//   console.log('The solution is: ', results[0].solution);
// });


